package cn.zqy.demo2.day11Net.BSTcp;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/*
    创建BS版本TCP服务器
 */
public class Demo02Server {
    public static void main(String[] args) throws IOException {
        ServerSocket server = new ServerSocket(8888);

         /*
            浏览器解析服务器回写的html页面,页面中如果有图片,那么浏览器就会单独的开启一个线程,读取服务器的图片
            我们就的让服务器一直处于监听状态,客户端请求一次,服务器就回写一次
         */
        while (true) {
            Socket socket = server.accept();

            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        InputStream is = socket.getInputStream();
                        BufferedReader br = new BufferedReader(new InputStreamReader(is));
                        String str = br.readLine();
                        String[] arr = str.split(" ");
                        String url = arr[1].substring(1);

                        File fs = new File(url);
                        if (!fs.exists()) {
                            System.out.println("文件夹不存在");
                            return;
                        }
                        System.out.println(url);
                        FileInputStream fis = new FileInputStream(url);
                        OutputStream os = socket.getOutputStream();
                        // 写入HTTP协议响应头,固定写法
                        os.write("HTTP/1.1 200 OK\r\n".getBytes());
                        os.write("Content-Type:text/html\r\n".getBytes());
                        // 必须要写入空行,否则浏览器不解析
                        os.write("\r\n".getBytes());

                        int len = 0;
                        byte[] b = new byte[1024];
                        while ((len = fis.read(b)) != -1) {
                            os.write(b,0,len);
                        }


                        fis.close();
                        socket.close();
                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                    }
                }
            }).start();

        }
    }
}
